package org.maitaole.controller;

import org.maitaole.bean.ValidateCode;
import org.maitaole.commons.Constant;
import org.maitaole.utils.ImageVerificationCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码
 */
@Controller
@RequestMapping("/captcha")
public class CaptchaController {

    /**
     * @Value("${code.expire}") 会将 properties 文件中的值自动的注入进来
     */
    @Value("${code.expire}")
    private String expire;

    @GetMapping
    public void initCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
//        System.out.println(expire);
        // 生产验证码
        ImageVerificationCode ivc = new ImageVerificationCode();
        // 生产验证码图片
        BufferedImage bufferedImage = ivc.getImage();
        // 获取到图片上的文字
        String text = ivc.getText();

        ValidateCode validateCode = new ValidateCode(text, Long.valueOf(expire));

        // 将图片验证码信息设置到session中
        session.setAttribute(Constant.VALIDATE_CODE_ATTR, validateCode);

        ImageVerificationCode.output(bufferedImage, response.getOutputStream());
    }
}
